<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Utils\ResponseFactory;
use App\Http\Requests\admin\dictionary\DictionaryRequest;
use App\Http\Requests\admin\dictionary\UpdateDictionaryRequest;
use App\Models\Manager\Dictionary;
use Illuminate\Http\Request;

/**
 *
 */
class DictionaryController extends Controller
{

    /** 添加数据字典
     * @param DictionaryRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    function addDictionary(DictionaryRequest $request): \Illuminate\Http\JsonResponse
    {

        if (Dictionary::all()->where('name',$request->input('name'))->count()>0){
            return ResponseFactory::simpleResponse(false,"数据字典已存在");
        }
        $result = Dictionary::create($request->all());
        if ($result != null) {
            return ResponseFactory::simpleResponse(true, "添加成功");
        } else {
            return ResponseFactory::simpleResponse(false, "添加失败");
        }
    }

    /**对字典进行软删除
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    function removeDictionary(int $id)
    {
        $dictionary = Dictionary::all()->find($id);
        if ($dictionary->state) {
            $dictionary->state = false;
            $result = $dictionary->save();
            return ResponseFactory::simpleResponse($result);
        }else{
            return ResponseFactory::simpleResponse(false,"此项已经被删除了");
        }

    }

    /**修改字典内容
     * @param UpdateDictionaryRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    function updateDictionary(UpdateDictionaryRequest $request)
    {
        $dictionary = Dictionary::all()->find($request->input('id'));
        if ($dictionary!=null){
            $result = $dictionary->update($request->all('type','name','remark'));
            return ResponseFactory::simpleResponse($result);
        }else{
            return ResponseFactory::simpleResponse(false,"id不存在");
        }
    }

    /**查询字典数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    function selectDictionary(Request $request): \Illuminate\Http\JsonResponse
    {
        $params = $request->all('type', 'pageNum', 'pageSize');
        if ($request->has('type')) {
            if ($request->has(['pageNum','pageSize'])){
                $rows = Dictionary::all()->where('state',true)->where('type',$params['type'])->forPage($params['pageNum'],$params['pageSize'])->all();
            }else{
                $rows = Dictionary::all()->where('state',true)->where('type',$params['type'])->all();
            }
            return ResponseFactory::response(null,array_values($rows));
        } else {
            $rows = Dictionary::all()->where('state',true);
            return ResponseFactory::response(null,$rows);
        }
    }
}
